package com.itchen.controller.module;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itchen.annotation.Log;
import com.itchen.common.PageResult;
import com.itchen.common.Result;
import com.itchen.domain.entity.User;
import com.itchen.service.UserService;
import com.itchen.utils.JwtTokenUtils;
import com.itchen.utils.PasswordUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * 用户 Controller
 */
@Tag(name = "用户管理", description = "用户相关接口")
@RestController
@RequestMapping("/user")
public class UserController {

    private final UserService userService;
    
    // 注入文件控制器
    private final FileController fileController;

    public UserController(UserService userService, FileController fileController) {
        this.userService = userService;
        this.fileController = fileController;
    }

    @GetMapping("getAll")
    @Operation(summary = "获取所有用户信息")
    @Log(operationType = "查询", operationModule = "用户管理")
    public Result<List<User>> getAllUsers() {
        List<User> users = userService.list();
        return Result.success(users);
    }

    @GetMapping("getByPage")
    @Operation(summary = "根据Page获取用户信息")
    @Log(operationType = "查询", operationModule = "用户管理")
    public Result<PageResult<User>> getAllUsersByPage(Long pageNum, Long pageSize, String username, String phone) {
        // 创建查询条件
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();

        // 动态添加查询条件
        if (username != null && !username.isEmpty()) {
            queryWrapper.like("username", username);
        }

        if (phone != null && !phone.isEmpty()) {
            queryWrapper.like("phone", phone);
        }

        Page<User> page = userService.page(new Page<>(pageNum, pageSize), queryWrapper);
        return Result.success(page);
    }

    @GetMapping("getById/{id}")
    @Operation(summary = "根据ID获取用户")
    @Log(operationType = "查询", operationModule = "用户管理")
    public Result<User> getUserById(@PathVariable Long id) {
        return Result.success(userService.getById(id));
    }

    @PostMapping("save")
    @Operation(summary = "添加用户")
    @Log(operationType = "新增", operationModule = "用户管理")
    public Result<Boolean> addUser(@RequestBody User user) {
        User username = userService.getOne(new QueryWrapper<User>().eq("username", user.getUsername()));
        if (username != null) {
            return Result.error("用户名已存在");
        }

        String password = user.getPassword();
        user.setPassword(PasswordUtil.encrypt(password));

        return Result.success(userService.save(user));
    }

    @PutMapping("update")
    @Operation(summary = "更新用户")
    @Log(operationType = "修改", operationModule = "用户管理")
    public Result<Boolean> updateUser(@RequestBody User user) {
        // 如果密码为空或null，则不更新密码字段
        if (user.getPassword() == null || user.getPassword().isEmpty()) {
            User existingUser = userService.getById(user.getId());
            if (existingUser != null) {
                user.setPassword(existingUser.getPassword());
            }
        }
        return Result.success(userService.updateById(user));
    }

    @Operation(summary = "删除用户")
    @DeleteMapping("deleteById/{id}")
    @Log(operationType = "删除", operationModule = "用户管理")
    public Result<Boolean> deleteUser(@PathVariable Long id) {
        return Result.success(userService.removeById(id));
    }

    @GetMapping("getCurrentUser")
    @Operation(summary = "获取当前登录用户信息")
    @Log(operationType = "查询", operationModule = "用户管理")
    public Result<User> getCurrentUser() {
        User currentUser = JwtTokenUtils.getCurrentUser();
        if (currentUser == null) {
            return Result.error("用户未登录");
        }
        return Result.success(currentUser);
    }

    @PutMapping("changePassword")
    @Operation(summary = "修改密码")
    @Log(operationType = "修改", operationModule = "用户管理")
    public Result<Boolean> changePassword(@RequestBody Map<String, String> params) {
        Long userId = Long.parseLong(params.get("id"));
        String oldPassword = params.get("oldPassword");
        String newPassword = params.get("newPassword");

        User user = userService.getById(userId);
        if (user == null) {
            return Result.error("用户不存在");
        }

        // 验证旧密码
        if (!PasswordUtil.verify(oldPassword, user.getPassword())) {
            return Result.error("原密码错误");
        }

        // 更新密码
        user.setPassword(PasswordUtil.encrypt(newPassword));
        return Result.success(userService.updateById(user));
    }

    @PutMapping("resetPassword/{id}")
    @Operation(summary = "重置密码")
    @Log(operationType = "修改", operationModule = "用户管理")
    public Result<Boolean> resetPassword(@PathVariable Long id) {
        User user = userService.getById(id);
        if (user == null) {
            return Result.error("用户不存在");
        }

        // 更新密码
        user.setPassword(PasswordUtil.encrypt("123456"));
        return Result.success(userService.updateById(user));
    }
    
    @PostMapping("uploadAvatar")
    @Operation(summary = "上传用户头像")
    @Log(operationType = "上传", operationModule = "用户头像")
    public Result<String> uploadAvatar(@RequestParam("file") MultipartFile file, @RequestParam("userId") Long userId) throws IOException {
        if (file.isEmpty()) {
            return Result.error("上传的头像文件不能为空");
        }
        
        // 检查文件类型是否为图片
        String contentType = file.getContentType();
        if (contentType == null || !contentType.startsWith("image/")) {
            return Result.error("只能上传图片文件");
        }
        
        // 上传文件
        Result<String> uploadResult = fileController.upload(file);
        if (!uploadResult.isSuccess()) {
            return Result.error("头像上传失败：" + uploadResult.getMsg());
        }
        
        // 更新用户头像URL
        User user = userService.getById(userId);
        if (user == null) {
            return Result.error("用户不存在");
        }
        
        user.setAvatar(uploadResult.getData());
        boolean updated = userService.updateById(user);
        if (!updated) {
            return Result.error("用户头像信息更新失败");
        }
        
        return Result.success(uploadResult.getData());
    }
}